/**
* User: Oleksii Savchenko
* Date: 01.02.13
* Time: 16:38
*/
var express = require('express');
var app = express(),
    path = require("path"),
    application_root = __dirname,
    _ = require('../app/js/libs/helpers/underscore-min.js');

// Config
app.configure(function () {
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(express.static(path.join(__dirname, "../app")));
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

/**
 * Get Item(s) by field(s) name
 * JSON
 */
app.get('/api/items:data?', function(req, res){
    var resultQuery;
    if(req.query.sort){
        resultQuery = queryProcessing.sortByItem(req.query.sort);
    } else {
        resultQuery = queryProcessing.filterItems(req.query);
    }
    res.setHeader('Content-Type', 'application/json');
    res.send(resultQuery);
});

/**
 * Delete record
 */
app.delete('/api/items:data?', function(req, res){
    res.send(queryProcessing.deleteItemById(req.param('id')));
});

/**
 * UPDATE a Single Product by ID
 */
app.put('/api/items:data?', function (req, res){
    var updateRes = queryProcessing.updateItem(req.param('id'), req.body);
    res.send(updateRes);
});

/**
 * CREATE a Single record
 */
app.post('/api/items', function(req, res){
    var createRes = queryProcessing.createItem(req.body);
    res.send(createRes);
});

app.listen(3000);
console.log('Server is working! Listening on port 3000');


/**
 * Items for examples
 * @type {Array}
 */
var items = [
    {
        "id": 'item_2a',
        "name": "Audi",
        "price": 20250,
        "dimensions": {
            "lengths": 2.5,
            "width": 1.8,
            "height": 1.4
        }
    },
    {
        "id": 'item_3a',
        "name": "BMV",
        "price": 250500,
        "dimensions": {
            "lengths": 2,
            "width": 1.7,
            "height": 1.4
        }
    },
    {
        "id": 'item_4a',
        "name": "Ford",
        "price": 50650,
        "dimensions": {
            "lengths": 2.8,
            "width": 2,
            "height": 1.8
        }
    },
    {
        "id": 'item_5a',
        "name": "Wheel X18",
        "price": 150.2
    }
];

/**
 * Query Processing
 * @type {Object}
 */
var queryProcessing = {
    /**
     * Get item(s) by field(s) name
     * @param params
     * @return {Array}
     */
    filterItems: function(params){
        var self = this;
            return _.filter(items, function(item){
                return _.every(params, function(val, key){
                    return item[key] == val;
                });
            });
    },

    /**
     * Sort by item key
     * @param sortParam
     * @return {Array}
     */
    sortByItem: function(sortParam) {
        return _.sortBy(items, function(itemParam){
            if(sortParam === 'lengths' || sortParam === 'width' || sortParam === 'height'){
                if(itemParam.dimensions) {
                    return itemParam.dimensions[sortParam];
                }
            } else {
                return itemParam[sortParam];
            }
        })
    },

    /**
     * Delete element by id
     * @param id
     * @return {Boolean}
     */
    deleteItemById: function(id){
        var oldArrayLenght, newArrayLenght;
        oldArrayLenght = items.length;
        items = _.reject(items, function(item){
            return item['id'] == id;
        });
        newArrayLenght = items.length;
        return (oldArrayLenght > newArrayLenght) ? true : false;
    },

    /**
     * Create items
     * @param item
     * @return {String}
     */
    createItem: function(item){
        var newId;
        newId = _.uniqueId('item_');
        item.id = newId;
        items.push(item);
        return newId;
    },

    /**
     * Update items by id
     * @param id
     * @param newItem
     * @return {Boolean}
     */
    updateItem: function(id, newItem){
        var itemToUpdate = _.find(items, function(item){
            return item['id'] == id;
        });
        if (!itemToUpdate) {
            return false;
        } else {
            var newItem = _.extend(itemToUpdate, newItem);
            return _.isObject(newItem);
        }
    }
}
